package org.example.spring;

import org.example.spring.annotation.*;
import org.example.spring.factory.BeanPostProcessor;
import org.example.spring.factory.InitializingBean;

import java.beans.Introspector;
import java.io.File;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: qiu
 * @Date: 2025/11/18/17:09
 */
public class ApplicationContext {

    private static final String SINGLETON = "singleton";
    private Class configClass;
    private Map<String, BeanDefinition> beanDefinitionMap = new HashMap<>();
    private Map<String, Object> singletonObjects = new HashMap<>();
    private List<BeanPostProcessor> beanPostProcessorList = new ArrayList<>();

    public ApplicationContext(Class configClass) {
        this.configClass = configClass;
        // 扫描配置路径
        scan();
        // 创建bean
        for (Map.Entry<String, BeanDefinition> entry : beanDefinitionMap.entrySet()) {
            String beanName = entry.getKey();
            BeanDefinition beanDefinition = entry.getValue();
            if (SINGLETON.equals(beanDefinition.getScope())) {
                Object bean = createBean(beanDefinition);
                // 放入单例池
                singletonObjects.put(beanName, bean);
            }
        }
    }

    /**
     * 创建bean
     * @param beanDefinition
     * @return
     */
    private Object createBean(BeanDefinition beanDefinition) {
        Class clazz = beanDefinition.getType();
        Object instance = null;
        try {
            instance = clazz.getConstructor().newInstance();

            // 依赖注入
            for (Field field : clazz.getDeclaredFields()) {
                if (field.isAnnotationPresent(Autowired.class)) {
                    field.setAccessible(true);
                    field.set(instance, getBean(field.getName()));
                }
            }

            // 实例化前
            for (BeanPostProcessor beanPostProcessor : beanPostProcessorList) {
                beanPostProcessor.postProcessBeforeInitialization(instance, Introspector.decapitalize(clazz.getSimpleName()));
            }

            // 实例化
            if (instance instanceof InitializingBean) {
                ((InitializingBean) instance).afterPropertiesSet();
            }

            // 实例化后
            for (BeanPostProcessor beanPostProcessor : beanPostProcessorList) {
                beanPostProcessor.postProcessAfterInitialization(instance, Introspector.decapitalize(clazz.getSimpleName()));
            }

        } catch (InstantiationException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        }
        return instance;
    }

    /**
     * 获取bean
     * @param beanName
     * @return
     */
    public Object getBean(String beanName) {
        if (!beanDefinitionMap.containsKey(beanName)) {
            return null;
        }
        BeanDefinition beanDefinition = beanDefinitionMap.get(beanName);
        Object bean = null;
        if (SINGLETON.equals(beanDefinition.getScope())) {
            bean = singletonObjects.get(beanName);
            // 依赖注入时，单例池没获取到
            if (bean == null) {
                bean = createBean(beanDefinition);
                singletonObjects.put(beanName, bean);
            }
        } else {
            bean = createBean(beanDefinition);
        }
        return bean;
    }

    /**
     * 扫描配置类上@componentScan的路径，并加载bean
     */
    private void scan() {
        if (configClass.isAnnotationPresent(ComponentScan.class)) {
            ComponentScan annotation = (ComponentScan) configClass.getAnnotation(ComponentScan.class);
            String packagePath = annotation.value();

            // 使用appClassLoader加载类
            ClassLoader classLoader = this.getClass().getClassLoader();
            URL resource = classLoader.getResource(packagePath.replace(".", "/"));
            File file = new File(resource.getFile());

            if (file.isDirectory()) {
                for (File f : file.listFiles()) {
                    try {
                        // 把.class加载到jvm中
                        Class clazz = classLoader.loadClass(packagePath + "." + f.getName().replace(".class", ""));
                        // @Component
                        if (clazz.isAnnotationPresent(Component.class)) {
                            Component componentAnno = (Component) clazz.getAnnotation(Component.class);
                            // 默认beanName为类名首字母小写
                            String beanName = componentAnno.value().equals("") ? Introspector.decapitalize(clazz.getSimpleName()) : componentAnno.value();

                            BeanDefinition beanDefinition = new BeanDefinition();
                            beanDefinition.setType(clazz);
                            // @Scope
                            Scope scopeAnno = (Scope) clazz.getAnnotation(Scope.class);
                            beanDefinition.setScope(scopeAnno == null ? SINGLETON : scopeAnno.value());
                            // @Lazy
                            if (clazz.isAnnotationPresent(Lazy.class)) {
                                beanDefinition.setLazy(true);
                            }
                            // 放入容器中
                            beanDefinitionMap.put(beanName, beanDefinition);

                            // bean是否实现了BeanPostProcessor
                            if (BeanPostProcessor.class.isAssignableFrom(clazz)) {
                                beanPostProcessorList.add((BeanPostProcessor) clazz.getConstructor().newInstance());
                            }
                        }
                    } catch (ClassNotFoundException e) {
                        throw new RuntimeException(e);
                    } catch (InvocationTargetException e) {
                        throw new RuntimeException(e);
                    } catch (InstantiationException e) {
                        throw new RuntimeException(e);
                    } catch (IllegalAccessException e) {
                        throw new RuntimeException(e);
                    } catch (NoSuchMethodException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        }
    }
}
